﻿using Abp.Application.Services.Dto;
using Abp.Application.Services;
using Choucius.Boilerplate9.OutboundTasks.Dto;
using Abp.Domain.Repositories;
using Abp.Collections.Extensions;
using System.Linq;
using Choucius.Boilerplate9.DtoBase.MES;
using System.Collections.Generic;
using Choucius.Boilerplate9.WorkStations;
using System.Threading.Tasks;
using Choucius.Boilerplate9.ProductContainerRelationships;
using System;
using Abp.EntityFrameworkCore.Repositories;

namespace Choucius.Boilerplate9.OutboundTasks
{
    /// <summary>
    /// 出库任务（MES下发）
    /// </summary>
    public class OutboundTaskAppService : AsyncCrudAppService<OutboundTask, OutboundTaskDto, int, PagedResultRequestDto, CreateOutboundTaskDto, OutboundTaskDto>, IOutboundTaskAppService
    {
        private readonly IRepository<OutboundTask, int> _repository;
        private readonly IWorkStationAppService _workStationAppService;
        private readonly IProductContainerRelationshipAppService _productContainerRelationshipAppService;

        public OutboundTaskAppService(IRepository<OutboundTask, int> repository) : base(repository)
        {
            _repository = repository;
        }

        public OutboundTaskAppService(IRepository<OutboundTask, int> repository, IWorkStationAppService workStationAppService, IProductContainerRelationshipAppService productContainerRelationshipAppService) : this(repository)
        {
            _workStationAppService = workStationAppService;
            _productContainerRelationshipAppService = productContainerRelationshipAppService;
        }

        /// <summary>
        /// 根据工站ID获取当前（明日）出库任务
        /// </summary>
        /// <param name="workStationId">工站ID</param>
        /// <returns>出库任务</returns>
        public OutboundTask GetCurrentTaskByWorkStation(int workStationId)
        {
            var outboundTask = _repository.GetAll()
                .WhereIf(workStationId > 0, p => p.WorkStationId == workStationId && p.PlanProduceDate >= DateTime.Today)
                .OrderByDescending(t => t.Id)
                .FirstOrDefault();
            return outboundTask;
        }

        /// <summary>
        /// 根据MES的工单，创建出库任务
        /// </summary>
        /// <param name="inputs">MES工单集合</param>
        /// <remarks>（因存在删除操作，不可异步）</remarks>
        public async Task CreateOutboundTaskFromMesAsync(List<MesDsDto> inputs)
        {
            if (inputs == null || inputs.Count == 0)
            {
                return;
            }
            // 删除全部
            var entities = _repository.GetAllList();
            _repository.RemoveRange(entities);
            // 写入
            foreach (var input in inputs)
            {
                List<int> workStationIds = _workStationAppService.GetAllWorkStationIds();
                if (workStationIds.Contains(input.EquipmentID))
                {
                    //var toBeDeleted = _repository.GetAllList().Where(x => x.WorkStationId == input.EquipmentID && x.BillNumber == input.BillNO && x.ProductErpId == input.ProductCode);
                    //if (toBeDeleted.Any())
                    //{
                    //    foreach (var workStation in toBeDeleted)
                    //    {
                    //        _repository.Delete(workStation);
                    //    }
                    //}

                    var entity = new OutboundTask();
                    DateTime dateTime;
                    entity.BillDate = DateTime.TryParse(input.BillDate, out dateTime) ? dateTime : null;
                    entity.BillNumber = input.BillNO;
                    entity.ProductErpId = input.ProductCode;
                    entity.ProductName = input.ProductName;
                    entity.WorkStationId = input.EquipmentID;
                    entity.ProductionQuantity = input.RPlanNum;
                    entity.NeedInunction = input.isoil;
                    entity.PlasticContainerQuantity = _productContainerRelationshipAppService.GetQuantityPerPlasticContainerByProduct(input.ProductCode);
                    entity.PlanProduceDate = DateTime.TryParse(input.PlanStartTime, out dateTime) ? dateTime : null;
                    entity.TaskStatus = "待出库";
                    _repository.Insert(entity);
                }
            }
        }
    }
}
